本文同步發表於個人網站
Lua的分支控制條件就僅有這麼一組:if-then/elseif-then/else/end

和其他語言一樣,elseif可以出現多次。你想用else if寫成巢狀也沒人會管你。他們兩個寫起來也真的蠻像的,除了你可能要多寫幾次end:
if true then
print("if block")
elseif true then
print("elseif block")
else
print("else")
end
if true then
print("if block")
else if true then
print("elseif block")
else
print("else")
end
end
注意到最後有兩個end。實際上我試故意將他這樣排版的,這樣兩個看起來比較像。
通常需要使用到巢狀分支,還是好好縮排比較好。

雖然只有if蠻簡單的,但有時候會想要使用switch這類結構。沒事,可以模擬:
option = "one"
switch = {
["one"] = function () print "run one" end,
["tow"] = function () print "run two" end,
}
switch[option]() -- => run one
實際上可以這樣寫:
option = "one"
switch = {
one = function () print "run one" end,
tow = function () print "run two" end,
}
switch[option]() -- => run one
這也算是Lua語法糖的一部分。不過我們等到hash-table在來說明。
熟悉ECMAScript的朋友可能已經猜到為什麼了。